package org.zjsru.order.service;

import org.springframework.transaction.annotation.Transactional;
import org.zjsru.order.mapper.OrderMapper;
import org.zjsru.order.pojo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zjsru.order.pojo.User;
import org.zjsru.order.pojo.Product;
import org.zjsru.order.web.ProductFeignClient;
import lombok.extern.slf4j.Slf4j;
import java.math.BigDecimal;

@Slf4j
@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderServiceFeign orderServiceFeign;

    @Autowired(required = false) // feign客户端可能不需要在订单服务中直接使用，先设置为非必须
    private ProductFeignClient productFeignClient;

    public Order queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        // 4.返回
        return order;
    }

    @Transactional
    public Long createOrder(Order order) {
        log.info("开始创建订单：userId={}, productId={}, num={}", order.getUserId(), order.getProductId(), order.getNum());

        // 1. 参数校验
        if (order == null || order.getUserId() == null || order.getProductId() == null || order.getNum() == null || order.getNum() <= 0) {
            throw new IllegalArgumentException("订单参数不完整或数量无效");
        }

        // 2. 调用 user-service 验证用户有效性
        try {
            User user = orderServiceFeign.checkUserStatus(order.getUserId());
            if (user == null) {
                 throw new RuntimeException("用户状态异常或不存在");
            }
            log.info("用户 {} 验证通过", order.getUserId());
        } catch (Exception e) {
            log.error("用户 {} 验证失败: {}", order.getUserId(), e.getMessage());
            throw new RuntimeException("用户验证失败: " + e.getMessage(), e); // 抛出运行时异常以触发事务回滚
        }

        // 3. 调用 product-service 获取商品详情并计算总金额
        Product product = null;
        try {
             // 传入用户ID到请求头
             // Note: In the original flow, productFeignClient was used here, but now payment service handles product details and price calculation.
             // We might need to adjust this if order creation still needs product price for total amount.
             // For now, assuming price comes with the initial order request or is handled differently.
             // Reverting to a simplified product fetch for order detail if needed, or assuming totalAmount is provided.

             // Assuming totalAmount is calculated based on product details fetched elsewhere or passed in the order object
             // If product price is still needed here, we would need a way to get it without calling product service directly if payment service is the one interacting.
             // Let's assume for simplicity totalAmount is calculated or passed in, or we fetch product details without triggering full product service logic intended for payment.

             // Re-checking previous code, the productFeignClient was used to get product detail *before* deducting stock.
             // This product detail (especially price) is needed to calculate total amount for the order.
             // So, fetching product detail here is still necessary for order creation.
             product = productFeignClient.getProductDetail(order.getProductId(), order.getUserId());
              if (product == null || product.getPrice() == null) {
                   throw new RuntimeException("无法获取商品详情或价格");
              }
              // 计算总金额
              BigDecimal totalAmount = product.getPrice().multiply(new BigDecimal(order.getNum()));
              order.setTotalAmount(totalAmount);
              log.info("商品 {} 价格获取成功，总金额: {}", order.getProductId(), totalAmount);

        } catch (Exception e) {
             log.error("获取商品详情或计算总金额失败: {}", e.getMessage());
             throw new RuntimeException("获取商品详情或计算总金额失败: " + e.getMessage(), e); // 抛出运行时异常以触发事务回滚
        }

        // 4. 插入订单数据
        orderMapper.insert(order);

        // 5. 返回订单ID（假设insert方法会设置order的id属性）
        return order.getId();
    }

    @Transactional
    public void updateOrderStatus(Long orderId, String status) {
        log.info("更新订单状态：orderId={}, status={}", orderId, status);
        int rows = orderMapper.updateOrderStatus(orderId, status);
        if (rows != 1) {
            throw new RuntimeException("更新订单状态失败，订单不存在或状态未改变");
        }
    }
}
